﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

namespace SAServices.Model
{
    class ConnectionConext
    {
        private SqlConnection m_sqlConn;
        private string m_serverName;
        private string m_userName;
        private string m_password;
        private string m_connectionString=null;
        private static string CONNSTRING_FORMAT = @"Data Source={0};Initial Catalog = XunPanDB; User Id = {1}; Password = {2};";
        //private static string CONNSTRING_FORMAT1 = @"Data Source={0};Initial Catalog=XunPanDB;Integrated Security=SSPI";

        public ConnectionConext(string serverName, string userName, string password)
        {
            m_serverName = serverName;
            m_userName = userName;
            m_password = password;

            //sql connection string.
            //
            if (String.IsNullOrEmpty(userName))
            {
                //add by jiang 2011115 start
                //m_connectionString = String.Format(CONNSTRING_FORMAT1, m_serverName);
                m_connectionString = ConfigurationManager.ConnectionStrings["XunPanConnectionString"].ToString();
                //add by jiang 2011115 end
            }
            else
            {
                m_connectionString = String.Format(CONNSTRING_FORMAT, m_serverName, userName, password);
            }
            //m_connectionString = String.Format(CONNSTRING_FORMAT, m_serverName, m_userName, m_password);


            m_sqlConn = GetOpenSqlConn();
        }

        public SqlConnection GetOpenSqlConn()
        {
            if (m_sqlConn == null)
            {
                m_sqlConn = new SqlConnection(m_connectionString);
            }

            if (m_sqlConn.State == ConnectionState.Closed || m_sqlConn.State == ConnectionState.Broken)
            {
                m_sqlConn.Open();
            }

            return m_sqlConn;
        }

        public bool TestConnection()
        {
            if (m_sqlConn == null)
            {
                return false;
            }

            if (m_sqlConn.State == ConnectionState.Open)
            {
                return true;
            }

            //try to open this connection.
            //
            //m_sqlConn.Open();

            //if (m_sqlConn.State == ConnectionState.Open)
            //{
            //    return true;
            //}

            return false;
        }

        public void Close()
        {
            if (m_sqlConn != null && m_sqlConn.State == ConnectionState.Open)
            {
                m_sqlConn.Close();
            }
        }
    }
}
